<template>
	<div class="page-login">
		<el-card style="width: 480px">
			<template #header>
				<div class="card-header">
					<span>登录</span>
				</div>
			</template>
			<div class="login-form">
				<el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
					label-width="80" class="demo-ruleForm">
					<el-form-item label="账号" prop="UserName">
						<el-input v-model="ruleForm.username" type="text" autocomplete="off" />
					</el-form-item>
					<el-form-item label="密码" prop="Password">
						<el-input v-model="ruleForm.password" type="password" autocomplete="off" />
					</el-form-item>
					<el-form-item label="验证码" prop="Code">
						<el-input v-model.number="ruleForm.code" maxlength="4" style="width: 70%;" />
						<el-image @click="refreshCaptcha" :src="captchaSrc"></el-image>
					</el-form-item>
					
					<el-form-item class="submitBtn">
						<el-button type="primary" @click="submitForm(ruleFormRef)">
							登录
						</el-button>
						<el-button @click="resetForm(ruleFormRef)">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
			<template #footer>Sun 设计</template>
		</el-card>
	</div>
</template>

<script lang="ts" setup>
	import { reactive, ref } from 'vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import { useStore } from '@/store/userStore'
	import { useRouter } from 'vue-router'
	import { ElMessage } from 'element-plus'
	import { loginRequest } from '@/api/user'

	const router = useRouter() // 获取路由实例，用于导航到其他页面等操作。
	const userStore = useStore() // 获取pinia实例，用于存储用户信息等操作。
	const captchaSrc = ref('http://127.0.0.1:8000/api/admin/verify_code?'+Date.now()) // 存储验证码图片的地址。

	const ruleFormRef = ref<FormInstance>()

	const checkCode = (rule : any, value : any, callback : any) => {
		if (!value) {
			return callback(new Error('验证码不能为空!'))
		}else{
			callback() // 验证通过
		}
	}

	const validateName = (rule : any, value : any, callback : any) => {
		if (value === '') {
			callback(new Error('账号不能为空!'))
		}else{
			callback() // 验证通过
		}
	}
	const validatePass = (rule : any, value : any, callback : any) => {
		if (value === '') {
			callback(new Error('密码不能为空!'))
		} else {
			callback() // 验证通过
		}
	}

	const ruleForm = reactive({
		username: 'admin',
		password: '123',
		code: '',
	})

	const rules = reactive<FormRules<typeof ruleForm>>({
		username: [{ validator: validateName, trigger: 'blur' }],
		password: [{ validator: validatePass, trigger: 'blur' }],
		code: [{ validator: checkCode, trigger: 'blur' }],
	})


	const submitForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.validate((valid) => {
			if (valid) {
				loginRequest(ruleForm).then(res => {
					window.localStorage.setItem('token', res.access) // 存储token，用于后续请求的验证。
					router.push('/') 
					return false
					// if (res.code == 200) {
					// 	console.log('获取数据成功!')
					// 	userStore.setUserInfo(res.data) // 存储用户信息
					// 	router.push('/') // 导航到其他页面
					// }
				}).catch(err => {
					console.log('获取数据失败!')
				})
				console.log('submit!')
			} else {
				 ElMessage.error('验证失败!')
			}
		})
	}

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}
	
	const refreshCaptcha = ()=>{
		captchaSrc.value = 'http://127.0.0.1:8000/api/admin/verify_code?' + Date.now(); // 更新验证码路径，实现刷新
	}
	
</script>

<style lang="scss" scoped>
	.page-login {
		width: 100%;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		background: url('https://images.pexels.com/photos/290595/pexels-photo-290595.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1');
		background-size: 100%;

		.submitBtn {
			margin: 40px auto 20px;

			:deep .el-form-item__content {
				justify-content: center;
			}
		}
	}
</style>